package boc.sx.gateway.socket.server.handler;

import boc.sx.gateway.core.RequestRoute;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
import io.netty.handler.codec.http.multipart.MemoryAttribute;
import io.netty.util.CharsetUtil;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        if(request.decoderResult().isFailure()){
            ctx.write(BAD_REQUEST);
            return;
        }
        JSONObject jsonRootObj = new JSONObject();
        // 获取传递的数据
        Map params = getParamsFromChannel(ctx, request);
        jsonRootObj.put("data", params);
        String serverCode = null;
        if(params.containsKey("serverCode") && params.get("serverCode") instanceof String){
            serverCode = (String)params.get("serverCode");
        }
        // 请求转发
        Object receive = RequestRoute.sendMessageToTargetServer(params, serverCode);
        // 构造返回数据
        StringBuilder bufRespose = new StringBuilder();
        if(receive instanceof String){
            bufRespose.append((String)receive );
        }else if(receive instanceof JSONObject){
            bufRespose.append(((JSONObject) receive).toJSONString());
        }else{

        }
        // 创建响应消息体
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
        // 设置请求头
        response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
        // 如果长连接
        if(HttpHeaderUtil.isKeepAlive(request)){
            response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }
        ByteBuf buffer = Unpooled.copiedBuffer(bufRespose, CharsetUtil.UTF_8);
        response.content().writeBytes(buffer);
        buffer.release();
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    private static Map getParamsFromChannel(
            ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest)
            throws UnsupportedEncodingException {
        HttpHeaders headers = fullHttpRequest.headers();

        String strContentType = ((String) headers.get("Content-Type") ).trim();
        System.out.println("ContentType:" + strContentType);
        Map mapReturnData = new HashMap();
        if (fullHttpRequest.method() == HttpMethod.GET) {
            // 处理get请求
            QueryStringDecoder decoder = new QueryStringDecoder(
                    fullHttpRequest.uri());
            Map parame = decoder.parameters();
            for (Object o : parame.entrySet()) {
                Map.Entry entry = (Map.Entry )o;
                Object value = entry.getValue();
//                mapReturnData.put(entry.getKey(),entry.getValue());
//                mapReturnData.put(entry.getKey(), (JSONObject)(entry.getValue()).get(0));
            }
            mapReturnData = parame;
            System.out.println("GET方式：" + parame);
        } else if (fullHttpRequest.method() == HttpMethod.POST) {
            // 处理POST请求
            if (strContentType.contains("x-www-form-urlencoded")) {
                HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(
                        new DefaultHttpDataFactory(false), fullHttpRequest);
                List<InterfaceHttpData> postData = decoder.getBodyHttpDatas();
                for (InterfaceHttpData data : postData) {
                    if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
                        MemoryAttribute attribute = (MemoryAttribute) data;
                        mapReturnData.put(attribute.getName(),
                                attribute.getValue());
                    }
                }
            } else if (strContentType.contains("application/json")) {
                // 解析json数据
                ByteBuf content = fullHttpRequest.content();
                byte[] reqContent = new byte[content.readableBytes()];
                content.readBytes(reqContent);
                String strContent = new String(reqContent, "UTF-8");
                System.out.println("接收到的消息" + strContent);
                JSONObject jsonParamRoot = JSONObject.parseObject(strContent);
                for (String key : jsonParamRoot.keySet()) {
                    mapReturnData.put(key, jsonParamRoot.get(key));
                }
            } else {
                FullHttpResponse response = new DefaultFullHttpResponse(
                        HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                ctx.writeAndFlush(response).addListener(
                        ChannelFutureListener.CLOSE);
            }
            System.out.println("POST方式：" + mapReturnData);
        }
        return mapReturnData;
    }
}
